# @time     :2022/4/25
# @Author   :Simple
# @FileName :auto_download_driver
from jsonpath import jsonpath
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_manager.opera import OperaDriverManager

from config import BASE_CAPS_DIR
from util.handle_yaml import get_base_caps, write_yaml


def install_driver(browser):
    """
    自动获取与浏览器及其版本匹配的driver，返回driver文件路径
    :param browser:  比如：{'name':"chrome"}
    :return:
    """
    name = browser['name'].lower()
    if name == 'chrome':
        path = ChromeDriverManager().install()
        browser['path'] = path
        browser['driver'] = "-Dwebdriver.chrome.driver"
    elif name == 'firefox':
        path = GeckoDriverManager().install()
        browser['path'] = path
        browser['driver'] = "-Dwebdriver.firefox.profile"
    elif name == 'edge':
        # 使用chrome内核的Edge浏览器
        path = EdgeChromiumDriverManager().install()
        browser['path'] = path
        browser['driver'] = "-Dwebdriver.edge.driver"
    elif name == 'opera':
        path = OperaDriverManager().install()
        browser['path'] = path
        browser['driver'] = "-Dwebdriver.opera.driver"
    elif browser == 'safari':
        # safari浏览器暂时不变更
        pass
    else:
        # 若以上浏览器都没有，那么就报错，无法获取其他浏览器对应的driver
        raise ValueError(f"not find {name}-driver.")


def write_driver_path():
    """
    自动下载的浏览器对应的driver，并将文件路径写入yaml
    :return:
    """
    # 获取浏览器的配置文件，得到需要测试的浏览器
    base_driver = get_base_caps()
    browsers = jsonpath(base_driver, "$.browsers[*]")
    # 根据浏览器及其版本下载对应的driver，得到文件路径
    for i in range(len(browsers)):
        install_driver(browsers[i])
    # 将对应的driver保存路径写入配置文件中
    write_yaml(base_driver, BASE_CAPS_DIR)


if __name__ == '__main__':
    # 自动下载配置文件中浏览器对应的driver，并将保存路径写入配置文件
    write_driver_path()

